package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.Rest.Tags.*;
import com.burgeon.backend.Rest.User.GetRetailByVip;
import com.burgeon.backend.Rest.User.GetRetailItem;
import com.burgeon.backend.Rest.User.ModVipDataBos;
import com.burgeon.backend.Rest.User.item.FindItemList;
import com.burgeon.backend.Rest.coupon.bos.CreateCouponBos;
import com.burgeon.backend.Rest.coupon.util.CreateIntegral;
import com.burgeon.backend.Rest.coupon.xe.CreateCoupon;
import com.burgeon.backend.SHOP.entity.Complement;
import com.burgeon.backend.SHOP.entity.ComplementRecord;
import com.burgeon.backend.SHOP.entity.CouponType;
import com.burgeon.backend.SHOP.entity.EmpData;
import com.burgeon.backend.SHOP.entity.couponGift.CouponGiftItem;
import com.burgeon.backend.SHOP.entity.couponGift.CouponGiftVO;
import com.burgeon.backend.SHOP.mappers.AppComplementMapper;
import com.burgeon.backend.SHOP.mappers.AppCouponMapper;
import com.burgeon.backend.SHOP.rest.CreateIntegralByAward;
import com.burgeon.backend.SHOP.rest.GETUserByOpenid;
import com.burgeon.backend.SHOP.rest.GetUserEmp;
import com.burgeon.backend.SHOP.rest.ModVipEmp;
import com.burgeon.backend.SHOP.service.AppComplementService;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.entity.*;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponRestrictMapper;
import com.burgeon.backend.service.ex.ErrorDataException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AppComplementServiceImpl implements AppComplementService {
    private final static Log logger = LogFactory.getLog(AppComplementService.class);

    @Autowired
    private AppComplementMapper appComplementMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AppCouponMapper couponMapper;
    @Autowired
    private AppTemplateService appTemplateService;
    @Autowired
    private CouponRestrictMapper couponRestrictMapper;

    @Override
    public ArrayList<RetailRecordItem> getVipRetailItem(String id, String token) {
        Info info = GetInfoByToken(token);
        GetRetailItem getRetailItem = new GetRetailItem(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getRetailItem.getData(id);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());
        }
        return null;
    }

    @Override
    @Transactional
    public void PointsAreRedeemedForCoupons(String tid, String phone,String openid, String token) throws ErrorDataExceptionApp {
//发券扣积分

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        String dateString = sdf.format(new Date());
        Info info = accountMapper.GetTokenData(token);
        CouponType couponType = couponMapper.findCouponTypeById(tid);
        //判断vip积分
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            User user = getUserByOpenid.getData(openid);
            if (Integer.parseInt(user.getIntegral())<Integer.parseInt(couponType.getIntegral())){
                throw new ErrorDataExceptionApp("积分不足?快去完成任务");
            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }

        String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
        Coupon coupon = new Coupon();
        coupon.setName(couponType.getName());
        coupon.setCode(code);
        coupon.setVipCode(phone);
        coupon.setCreation(dateString);
        coupon.setTypeid(tid);
        coupon.setType(couponType.getType());
        coupon.setDiscount(couponType.getDiscount());
        coupon.setDatebeg(couponType.getDatebeg());
        coupon.setDateend(couponType.getDateend());
        coupon.setIntegral(couponType.getIntegral());
        coupon.setMoney(couponType.getMoney());
        coupon.setOriginal(couponType.getOriginal());
        coupon.setAccount(token);
        coupon.setToken(token);
        String source = "积分兑换";
        coupon.setSource(source);
        String inid = null;
        try {
            if ("BOS".equals(info.getSystem())) {
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());
                inid = createIntegral.getData(phone, couponType.getIntegral());
                coupon.setVipIntegral(inid);
                if (!"1".equals(couponType.getScene())) {
                    List<String> goods = new ArrayList<>();
                    List<String> stores = new ArrayList<>();

                    if (couponType.getRestrictProduct().equals("Y")){
                        goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

                    }
                    if (couponType.getRestrictStore().equals("Y")){
                        stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());
                    }

                    createCoupon.getData(coupon,goods,stores);
                }

            } else {
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                inid = createIntegral.getData(phone, couponType.getIntegral());
                coupon.setVipIntegral(inid);
                if (!"1".equals(couponType.getScene())) {
                    createCoupon.getData(coupon);
                }

            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "创建优惠券错误" + inid + ";" + phone);
            throw new ErrorDataExceptionApp(e.getMessage());
        }
        Integer row = couponMapper.addCoupon(coupon);

        if (row != 1) {
            logger.error("创建优惠券出错" + inid + ";" + phone);
            throw new ErrorDataException("出现错误");
        }
        coupon.setCreation(ssdf.format(new Date()));
        SimpleDateFormat sdft = new SimpleDateFormat("yyyyMMdd");
        try {
            coupon.setDateend(ssdf.format(sdft.parse(couponType.getDatebeg())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        appTemplateService.SendExchangeCoupon(coupon,phone,openid,token);

    }

    @Override
    @Transactional
    public void PointsAreRedeemedForGiftCoupons(String cid ,String[] tids, String phone, String openid, String token) throws Exception {

        //发券扣积分
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat ssdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");//消息模板使用
        String dateString = sdf.format(new Date());
        Info info = accountMapper.GetTokenData(token);

        //判断vip积分
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        Integer integer = couponMapper.findGiftIntegral(cid);
        try {
            User user = getUserByOpenid.getData(openid);
            if (Integer.parseInt(user.getIntegral())<integer){
                throw new ErrorDataExceptionApp("积分不足?快去完成任务");
            }
        } catch (Exception e) {
            throw new ErrorDataException(e.getMessage());
        }
        Coupon coupon = null;
        CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
        String inid = createIntegral.getData(phone, integer.toString());
        for (String tid:tids) {
            CouponType couponType = couponMapper.findCouponTypeById(tid);

            String code = create_nonce_str().replace("-", "").trim().substring(0, 8);
            coupon = new Coupon();
            coupon.setName(couponType.getName());
            coupon.setCode(code);
            coupon.setVipCode(phone);
            coupon.setCreation(dateString);
            coupon.setTypeid(tid);
            coupon.setType(couponType.getType());
            coupon.setDiscount(couponType.getDiscount());
            coupon.setDatebeg(couponType.getDatebeg());
            coupon.setDateend(couponType.getDateend());
            coupon.setIntegral(couponType.getIntegral());
            coupon.setMoney(couponType.getMoney());
            coupon.setOriginal(couponType.getOriginal());
            coupon.setAccount(token);
            coupon.setToken(token);
            String source = "积分兑换";
            coupon.setSource(source);
            try {
                if ("BOS".equals(info.getSystem())) {
                    CreateCouponBos createCoupon = new CreateCouponBos(info.getUrl(), info.getAccount(), info.getPassword());

                    coupon.setVipIntegral(inid);
                    if (!"1".equals(couponType.getScene())) {
                        List<String> goods = new ArrayList<>();
                        List<String> stores = new ArrayList<>();

                        if (couponType.getRestrictProduct().equals("Y")){
                            goods = couponRestrictMapper.getCouponTypeRestrictProduct(couponType.getId());

                        }
                        if (couponType.getRestrictStore().equals("Y")){
                            stores = couponRestrictMapper.getCouponTypeRestrictStore(couponType.getId());
                        }

                        createCoupon.getData(coupon,goods,stores);
                    }

                } else {
                    CreateCoupon createCoupon = new CreateCoupon(info.getUrl(), info.getAccount(), info.getPassword());
                    inid = createIntegral.getData(phone, integer.toString());
                    coupon.setVipIntegral(inid);
                    if (!"1".equals(couponType.getScene())) {
                        createCoupon.getData(coupon);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage() + "创建优惠券错误" + inid + ";" + phone);
                throw new ErrorDataExceptionApp(e.getMessage());
            }
            Integer row = couponMapper.addCoupon(coupon);

            if (row != 1) {
                logger.error("创建优惠券出错" + inid + ";" + phone);
                throw new ErrorDataException("出现错误");
            }
            coupon.setCreation(ssdf.format(new Date()));
            SimpleDateFormat sdft = new SimpleDateFormat("yyyyMMdd");
            try {
                coupon.setDateend(ssdf.format(sdft.parse(couponType.getDatebeg())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        appTemplateService.SendExchangeCoupon(coupon,phone,openid,token);

    }


    @Override
    public User getUserData(String openid, String token) {
        Info info = accountMapper.GetTokenData(token);
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            return getUserByOpenid.getData(openid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void modUserEmp(String phone,String openid, String emp, String token) {
        Info info = accountMapper.GetTokenData(token);
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(),info.getAccount(),info.getPassword());
        ModVipEmp modVipEmp = new ModVipEmp(info.getUrl(),info.getAccount(),info.getPassword());

        try {
            User erpuser = getUserByOpenid.getData(openid);
            if ("null".equals(erpuser.getEmp())){
                //加积分
                String integral = appComplementMapper.getEmpAward(token);
                CreateIntegralByAward createIntegralByAward = new CreateIntegralByAward(info.getUrl(),info.getAccount(),info.getPassword());
                createIntegralByAward.getData(phone,integral);
            }
          /*  if ("Y".equals(erpuser.getStorejh())){
                erpuser.setStorejh(emp);
            }*/
            erpuser.setStorejh(null);
            modVipEmp.getData(erpuser.getId(),emp,erpuser.getStorejh());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public HashMap userEmpData(String openid, String token) {
        Info info = accountMapper.GetTokenData(token);
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(),info.getAccount(),info.getPassword());
        GetUserEmp getUserEmp = new GetUserEmp(info.getUrl(),info.getAccount(),info.getPassword());
        HashMap data = new HashMap();
        try {
            User erpuser = getUserByOpenid.getData(openid);
            ArrayList<EmpData> emp = getUserEmp.getData(erpuser.getStore());
            if ("null".equals(erpuser.getEmp())){
                data.put("use","N");
            }else {
                data.put("use","Y");
            }
            String integral = appComplementMapper.getEmpAward(token);
            data.put("award",integral);
            data.put("store",erpuser.getStore());
            data.put("emp",emp);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void makeUserTags(String phone, VipAttrib vipAttrib, String cid, String token) throws ErrorDataException {
        System.err.println("phone="+phone+"cid="+cid+"token="+token);
        System.err.println(vipAttrib);
        Info info = accountMapper.GetTokenData(token);
        FindTagsIdByVip findTagsIdByVip = new FindTagsIdByVip(info.getUrl(), info.getAccount(), info.getPassword());
        ModVipTagsBos modVipTagsBos = new ModVipTagsBos(info.getUrl(), info.getAccount(), info.getPassword());
        InsertVipTagsBos insertVipTagsBos = new InsertVipTagsBos(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            modVipTagsBos.getData(findTagsIdByVip.getData(phone), vipAttrib);
        } catch (Exception e) {

            try {
                insertVipTagsBos.getData(phone, vipAttrib);
            } catch (Exception ex) {
                logger.error(e.getMessage()+"添加vip标签错误");

                throw new ErrorDataException("添加vip标签错误");
            }
        }
        //记录为null
        if (appComplementMapper.findVipRecord(cid,phone)==null){
            //创建记录
            ComplementRecord complementRecord = new ComplementRecord();
            complementRecord.setCode(cid);
            complementRecord.setUser(phone);
            appComplementMapper.addComplementRecord(complementRecord);
            //加积分
            String award = appComplementMapper.findAward(cid);
            CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                createIntegral.getData(phone,"-"+award);
            } catch (Exception e) {
                logger.error(e.getStackTrace());
                try {
                    createIntegral.getData(phone,award);
                } catch (Exception ex) {
                    logger.error("two"+ Arrays.toString(e.getStackTrace()));
                }
            }
        }
    }

    @Override
    public ArrayList<String> getTagsItem(String code, String token) {
        Info info = accountMapper.GetTokenData(token);
        FindTagsItem findTagsItem = new FindTagsItem(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            return findTagsItem.getData(code);
        } catch (Exception e) {
            logger.error(e.getMessage()+ Arrays.toString(e.getStackTrace()));
            return null;
        }
    }

    @Override
    public void delComplement(String id) throws ErrorDataException {
        try {
           appComplementMapper.delComplement(id);
        }catch (Exception e){
            logger.error(e.getStackTrace());
            throw new ErrorDataException("出现错误");
        }
    }

    @Override
    public void newComplementSwitch(Complement complement) throws ErrorDataException {
        try {
            appComplementMapper.addComplementSwitch(complement);
        }catch (Exception e){
            logger.error(e.getStackTrace());
            throw new ErrorDataException("创建失败,类型重复");
        }
    }

    @Override
    public List<Complement> getComplementSwitch(String phone,String account) throws ErrorDataException {
        Info info = GetInfoByToken(account);
        List<Complement> data = appComplementMapper.showComplementSwitch(account);
        List<String> rec = appComplementMapper.findRecord(phone);
        QueryTagsDataByVip queryTagsDataByVip = new QueryTagsDataByVip(info.getUrl(),info.getAccount(),info.getPassword());
        VipAttrib vipattrib = queryTagsDataByVip.getData(phone);
        for (Complement datum : data) {
            datum.setItem(setTags(vipattrib,datum.getCodeId()));
            datum.setUse("N");
            for (String s : rec) {
                if (datum.getId().equals(s)) {
                    datum.setUse("Y");
                }
            }
        }
        System.err.println(data);

        return data;
    }

    private String setTags(VipAttrib vipAttrib,String code){

        switch (code){
            case "1":
                return vipAttrib.getVipAttrib1();
            case "2":
                return vipAttrib.getVipAttrib2();
            case "3":
                return vipAttrib.getVipAttrib3();
            case "4":
                return vipAttrib.getVipAttrib4();
            case "5":
                return vipAttrib.getVipAttrib5();
            case "6":
                return vipAttrib.getVipAttrib6();
            case "7":
                return vipAttrib.getVipAttrib7();
            case "8":
                return vipAttrib.getVipAttrib8();
            case "9":
                return vipAttrib.getVipAttrib9();
            case "10":
                return vipAttrib.getVipAttrib10();
            case "11":
                return vipAttrib.getVipAttrib11();
            case "12":
                return vipAttrib.getVipAttrib12();
        }

        return null;
    }

    @Override
    public List<Complement> getComplement(String account) throws ErrorDataException {

        return appComplementMapper.showComplementSwitch(account);
    }

    @Override
    public void modVipData(String token, User user, String openid) throws ErrorDataException {
        Info info = accountMapper.GetTokenData(token);
        ModVipDataBos modVipDataBos = new ModVipDataBos(info.getUrl(),info.getAccount(),info.getPassword());
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            User erpuser = getUserByOpenid.getData(openid);
            modVipDataBos.getData(erpuser.getId(),user);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ErrorDataException("出现错误");
        }

    }
    /*******************************积分兑换*******************************************/
    @Override
    public List<CouponType> showRedeemCoupons(String token) throws ErrorDataException {
        //是积分商城未过期购物券类型
        ArrayList<CouponType> data = new ArrayList<>();
        List<CouponType> list =appComplementMapper.ConversionCoupon(token);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());

        for (CouponType ct : list) {
            if (Integer.parseInt(ct.getDateend()) >= Integer.parseInt(date)) {
                if (null==ct.getScene()){
                    ct.setScene("3");
                }
                data.add(ct);
            }
        }
        return data;
    }

    //套券积分展示
    @Override
    public List showGiftConversion(String token) {
        //是积分商城未过期购物券类型
        ArrayList<CouponGiftVO> data = new ArrayList<>();
        List<CouponGiftVO> list =appComplementMapper.showGiftConversion(token);

        for (CouponGiftVO cg : list) {

            List<CouponType> couponTypes = new ArrayList<>();

            Integer price = 0;

            List<CouponGiftItem> couponGiftItem = appComplementMapper.findCoupon(cg.getId());

            for (CouponGiftItem cgi:couponGiftItem) {
                for (int i = 0; i < cgi.getCount(); i++) {
                    CouponType couponType = appComplementMapper.findCouponData(cgi.getTid());
                    price += Integer.parseInt(couponType.getMoney());
                    couponTypes.add(couponType);
                }
            }
            cg.setCouponTypes(couponTypes);
            cg.setPrice(price.toString());
            data.add(cg);
        }
        return data;
    }



    /*******************************积分明细*******************************************/
    @Override
    public ArrayList<RechargeItem> getVipRechargeItem(String phone, String token) {
        Info info = GetInfoByToken(token);
        FindItemList findItemList = new FindItemList(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return findItemList.getData(phone);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());
            return null;
        }
    }

    /**
     * 消费记录
     * @param phone
     * @param token
     * @return
     */
    @Override
    public ArrayList<RetailRecord> getVipRetail(String phone, String token) {
        Info info = GetInfoByToken(token);
        GetRetailByVip getRetailByVip = new GetRetailByVip(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getRetailByVip.getData(phone);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());

        }
        return null;
    }



    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

}
